<template>
  <div class="form-comp">
    <div class="toolbar-item toolbar-select">
      <el-upload
          v-if="limit===1"
          :disabled="disabled"
          class="avatar-uploader"
          :action="action"
          :show-file-list="false"
          :headers="headers"
          :on-success="handleAvatarSuccess"
          :before-upload="beforeAvatarUpload"
      >
        <!-- 图片模式 -->
        <div class="avatar-icon" v-if="type=='image'">
          <img v-if="fileUri" :src="fileUri" class="avatar"/>
          <el-icon v-else class="avatar-uploader-icon">
            <Plus/>
          </el-icon>
        </div>
        <!-- 普通模式 -->
        <div class="upload-file-btn" v-else-if="type=='file'">
          <el-input v-model="fileUri" placeholder="请选择文件" :readonly="true">
            <template #append>
              <el-button type="primary">
                Upload
                <el-icon class="el-icon--right">
                  <Upload/>
                </el-icon>
              </el-button>
            </template>
          </el-input>
        </div>

      </el-upload>

      <el-upload
          :action="action"
          list-type="picture-card"
          :on-preview="handlePictureCardPreview"
          :on-remove="handleRemove"
          :headers="headers"
          :on-success="handleAvatarSuccess"
          :before-upload="beforeAvatarUpload"
      >
        <el-icon>
          <Plus/>
        </el-icon>
      </el-upload>

      <el-dialog v-model="dialogVisible">
        <img w-full :src="dialogImageUrl" alt="Preview Image"/>
      </el-dialog>

    </div>
  </div>

</template>

<script lang="ts" setup>
// @ts-ignore
import store from "@/conf/store";

defineOptions({
  name: "FormUpdateFile"
});
// @ts-ignore
import {getCurrentInstance, onMounted, ref, watch} from 'vue'
// @ts-ignore
import {ElMessage} from 'element-plus'
// @ts-ignore
import {Plus} from '@element-plus/icons-vue'
// @ts-ignore
import type {UploadProps} from 'element-plus'

//图片显示路径
const fileUri = ref('')
//

const showList = ref(true);

const headers = ref<any>();
//文件后缀
const suffix = ref<any>([]);

const emit = defineEmits(['update:value', 'update:fileSize', 'update:fileSuffix', 'update:originalName', "update:browser"])

// @ts-ignore
const {proxy} = getCurrentInstance()

//文件列表
const fileList = ref<any>([]);

const props = defineProps({
  label: {type: String, required: false},
  value: {type: String, required: true},
  fileSize: {type: String, required: false},
  fileSuffix: {type: String, required: false},
  originalName: {type: String, required: false},
  type: {type: String, required: false, default: 'file'},
  disabled: {type: Boolean, required: false},
  action: {type: String, default: '/api/file/uploadFile'},
  browser: {type: String, required: false},
  limit: {type: Number, default: 1}
});
//监听变化返回
watch(() => props.value, async () => {
  if (props.type === 'image' && !fileUri.value.startsWith("blob:")) {
    if (props.limit === 1) {
      fileUri.value = window.URL.createObjectURL(new Blob([(await proxy.$http.blob(props.value)).data], {type: 'application/pdf'}));
    } else {
      //多张图片处理
    }
  } else if (props.type !== 'image') {
    fileUri.value = props.value
  }
}, {
  // deep: true // 可以不写
})
onMounted(() => {
  headers.value = {
    authorization: 'bearer ' + store.getters.token
  }
  if (props.type === 'image') {
    showList.value = false;
    suffix.value.push('image/jpeg');
    suffix.value.push('image/png');
  } else if (props.type === 'file') {
    showList.value = false;
  } else if (props.type === 'word') {
    showList.value = false;
    suffix.value.push('application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
    suffix.value.push('application/vnd.ms-excel');
  } else if (props.type === 'excel') {
    suffix.value.push('application/vnd.openxmlformats-officedocument.wordprocessingml.document');
    suffix.value.push('application/msword');
    showList.value = false;
  }
})


const handleAvatarSuccess: UploadProps['onSuccess'] = (
    response,
    uploadFile
) => {
  if (props.type === 'image') {
    fileUri.value = URL.createObjectURL(uploadFile.raw!)
  } else if (props.type == 'file') {
    fileUri.value = response.browser;
  }
  fileList.value.push({
    name: response.originalName,
    browser: response.browser,
    filePath: response.filePath
  });

  if (props.limit === 1) {
    emit("update:value", response.filePath)
    emit("update:fileSize", response.fileSize)
    emit("update:fileSuffix", response.fileSuffix)
    emit("update:originalName", response.originalName)
    emit("update:browser", response.browser)
  } else {
    let browsers = "";
    let filePaths = "";
    console.log(fileList.value.length)
    for (let i = 0; i < fileList.value.length; i++) {
      if (i > 0) {
        browsers = browsers + ","
        filePaths = filePaths + ","
      }
      browsers = browsers + fileList.value[i].browser
      filePaths = filePaths + fileList.value[i].filePath

    }
    emit("update:browser", browsers)
    emit("update:value", filePaths)

  }
}

const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
  if (suffix.value.length > 0) {
    if (!suffix.value.includes(rawFile.type)) {
      ElMessage.error('Avatar picture must be ' + suffix.value.toLocaleString() + ' format!')
      return false
    }
  }
  if (rawFile.size / 1024 / 1024 > 5) {
    ElMessage.error('文件不能> 5MB!')
    return false
  }
  return true
}

const dialogImageUrl = ref('')
const dialogVisible = ref(false)

const handleRemove: UploadProps['onRemove'] = (uploadFile, uploadFiles) => {
  let browsers = "";
  let filePaths = "";
  fileList.value=[];
  for (let i = 0; i < uploadFiles.length; i++) {
    let response: any = uploadFiles[i].response;
    if (i > 0) {
      browsers = browsers + ","
      filePaths = filePaths + ","
    }
    browsers = browsers + response.browser
    filePaths = filePaths + response.filePath
    fileList.value.push({
      name: response.originalName,
      browser: response.browser,
      filePath: response.filePath
    });
  }
  emit("update:browser", browsers)
  emit("update:value", filePaths)
}

const handlePictureCardPreview: UploadProps['onPreview'] = (uploadFile) => {
  dialogImageUrl.value = uploadFile.url!
  dialogVisible.value = true
}

</script>

<style>

</style>
